<script lang='ts' setup>
import { ref, provide, watch, } from 'vue'
import type { NameType,CollapseProps,CollapseEmits  } from './type.d.ts'
import  { collapseContextKey } from './constant'
defineOptions({
  name: 'VkCollapse',
})

const props = defineProps<CollapseProps>()
const emits = defineEmits<CollapseEmits>()
const activeNames = ref<NameType[]>(props.modelValue)
watch(() => props.modelValue, () => {
  activeNames.value = props.modelValue
})

if (props.accordion && activeNames.value.length > 1) {
  console.warn('accordion mode should only have one acitve item')
}

const handleItemClick = (name: NameType) => {
  
  if (props.accordion) {
    activeNames.value = [ activeNames.value[0] === name ? '' : name ]
  } else {
    const index = activeNames.value.indexOf(name)
    if (index === -1) {
      activeNames.value.push(name)
    } else {
      activeNames.value.splice(index, 1)
    }
   
  }

  emits('update:modelValue', activeNames.value)
}

provide(collapseContextKey, {
  activeNames,
  handleItemClick,
})
</script>

<template>
 <div
    class="vk-collapse"
  >
    <slot></slot>
  </div>
</template>
<style scoped lang='less'></style>